﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;

namespace MicroLib
{
    public class Person
    {
        public string source = "sina";
        public string id;
        public string screen_name;
        public string name;
        public string province;
        public string city;
        public string location;
        public string description;
        public string url;
        public string profile_image_url;
        public string gender;
        public string createdTime;

        public Person(string xml)
        {
            string txtvalue;
            XmlDocument dom = new XmlDocument();
            dom.LoadXml(xml);
            XmlNodeList nodes = dom.SelectNodes("user/*");
            foreach (XmlNode node in nodes)
            {
                txtvalue = node.InnerText.Replace("'","`");
                txtvalue = txtvalue.Replace("\\", " ");
                txtvalue = txtvalue.Replace("\"", "`");

                switch (node.Name)
                {
                    case "id":
                        id = txtvalue;
                        break;
                    case "screen_name":
                        screen_name = txtvalue;
                        break;
                    case "name":
                        name = txtvalue;
                        break;
                    case "province":
                        province = txtvalue;
                        break;
                    case "city":
                        city = txtvalue;
                        break;
                    case "location":
                        location = txtvalue;
                        break;
                    case "description":
                        description = txtvalue;
                        break;
                    case "url":
                        url = txtvalue;
                        break;
                    case "profile_image_url":
                        profile_image_url = txtvalue;
                        break;
                    case "gender":
                        gender = txtvalue;
                        break;
                    case "created_at":
                        createdTime = txtvalue;
                        break;
                    default:
                        break;
                }
            }
        }
    }
    public class MicroBlogSina
    {
        private string userName;
        private string Password;
        private oAuthSina oauth = new oAuthSina();
        string basic = "http://api.t.sina.com.cn/";//"http://api.weibo.com/";
        string webbasic = "http://t.sina.com.cn/";

        public MicroBlogSina()
        {
           
        }
        public bool Login(string username, string password,string cookie)
        {
            userName = username;
            Password = password;
            if (cookie != "" && cookie != null)
            {
                oauth.LoginWithCookie(cookie);
            }
            else 
                oauth.Login(username, password);

            return true;
        }
        public bool Post(string content)
        {

            string url = basic + "statuses/update.xml?";
            string retMsg = oauth.oAuthWebRequest(oAuthSina.Method.POST, url, "status=" + HttpUtility.UrlEncode(content));
            return true;    
        }
        public bool Reply(string id, string content)
        {
            string retMsg;
            string url = basic + "users/show.xml";
            retMsg = oauth.oAuthWebRequest(oAuthSina.Method.GET, url+ "?user_id=" + id,string.Empty);

            XmlDocument dom = new XmlDocument();
            dom.LoadXml(retMsg);
            XmlNode nodeText=dom.SelectSingleNode("//user//status//id");
            string msgId = nodeText.InnerText;

            url = basic + "statuses/comment.xml?";
            retMsg = oauth.oAuthWebRequest(oAuthSina.Method.POST, url, "id=" + HttpUtility.UrlEncode(msgId)+"&comment="+HttpUtility.UrlEncode(content));

            return true;
        }
        public bool Post2Group(string groupid, string content)
        {
            Reply(groupid, content);
            return true;
        }
        public void At2People(string username, string content)
        {
            Post("@" + username + " " + content);
        }
       
        private XmlDocument parseHTML(string html)
        {
            string pattern;
            XmlDocument dom=new XmlDocument();
            
            XmlNode users=dom.CreateNode("element","users","");
            users.InnerXml="<next_cursor></next_cursor><previous_cursor></previous_cursor>";
            dom.AppendChild(users);
            
            int tmp=html.IndexOf("<!--左栏内容 -->");
            int index=-1;
            while((index=html.IndexOf("<div class=\"conBox_l\">",tmp))!=-1)
            {
                index=html.IndexOf("<img pop=\"true\"",index);
                if(index==-1)
                    continue;

                pattern="title=\"";
                index=html.IndexOf(pattern,index)+pattern.Length;
                string name=html.Substring(index,html.IndexOf("\"",index)-index);

                pattern="uid=\"";
                index=html.IndexOf(pattern,index)+pattern.Length;
                string userid=html.Substring(index,html.IndexOf("\"",index)-index);

                pattern="src=\"";
                index=html.IndexOf(pattern,index)+pattern.Length;
                string imgurl=html.Substring(index,html.IndexOf("\"",index)-index);

                index=html.IndexOf("<img src=\"",index);

                pattern="title=\"";
                index=html.IndexOf(pattern,index)+pattern.Length;
                string sex=html.Substring(index,html.IndexOf("\"",index)-index);
                sex=sex.Replace("男","m");
                sex=sex.Replace("女","f");

                pattern="/>";
                index=html.IndexOf(pattern,index)+pattern.Length;
                string location=html.Substring(index,html.IndexOf("<span>",index)-index);

                tmp = index;
                XmlNode user=dom.CreateNode("element", "user", "");
                user.InnerXml = "<id>"+userid+"</id><screen_name>"+name+"</screen_name><name>"+name+"</name><province>-1</province><city>-1</city><location>"+location+"</location><description/><created_at/><url/>"+
                "<profile_image_url>"+imgurl+"</profile_image_url><gender>"+sex+"</gender>";

                users.AppendChild(user);

            };
            string nextpage,previousPage;
            index = html.IndexOf("fanye MIB_txtbl rt", tmp);
            if (index != -1)
            {
                pattern = "<span>";
                index = html.IndexOf(pattern, index) + pattern.Length;
                previousPage = html.Substring(index, html.IndexOf("</span>", index) - index);

                if (previousPage == "...")
                {
                    index = html.IndexOf(pattern, index) + pattern.Length;
                    previousPage = html.Substring(index, html.IndexOf("</span>", index) - index);
                }

                index = html.IndexOf("<a class=\"btn_num\" href", index);
                if (index == -1)
                    nextpage = "0";
                else
                {
                    pattern = "<em>";
                    index = html.IndexOf(pattern, index) + pattern.Length;
                    nextpage = html.Substring(index, html.IndexOf("</em>", index) - index);
                }
            }
            else
            {
                nextpage = "0";
                previousPage = "1";
            }

            dom.SelectSingleNode("users/next_cursor").InnerText=nextpage;
            dom.SelectSingleNode("users/previous_cursor").InnerText = previousPage;

            return dom;
        }

        //use web browser way
        public Person[] GetFollowers2(string userid, ref string cursor)
        {
            string retMsg;

            if(cursor=="-1")
                cursor ="1";

            string url = webbasic + "attention/att_list.php?action=1&uid="+userid+"&tag=&page="+cursor;
            retMsg = oauth.oAuthWebRequest(oAuthSina.Method.GET, url, "");

            XmlDocument dom = parseHTML(retMsg);

            XmlNodeList nodes = dom.SelectNodes("users/user");

            int len = nodes.Count;
            Person[] fans=new Person[len];
            int i = 0;
            foreach (XmlNode node in nodes)
            {
                  fans[i++]= new Person (node.OuterXml);
            }

            XmlNode xcursor = dom.SelectSingleNode("users/next_cursor");
            cursor = xcursor.InnerText;

            return fans;
        }
        public Person[] GetUserDetails2(string userid)
        {
            string retMsg;
            string url = basic + "users/show.xml";
            retMsg = oauth.oAuthWebRequest(oAuthSina.Method.GET, url+ "?user_id=" + userid,string.Empty );
            
            Person ret = new Person(retMsg);
            Person[] tmp = new Person[1];
            tmp[0] = ret;
            return tmp;
        }
        public void Logout()
        {
            string url = basic + "account/end_session.xml";
            oauth.oAuthWebRequest(oAuthSina.Method.GET, url, string.Empty);
            oauth.token = string.Empty;
            oauth.tokenSecret = string.Empty;
            oauth.Verifier = string.Empty;
            

        }
        public Person[] GetFollowers(string userid, ref string cursor)
        {
            string count="100";
            string retMsg;
            string url = basic + "statuses/followers.xml";
            retMsg = oauth.oAuthWebRequest(oAuthSina.Method.GET, url+ "?user_id=" + userid+"&cursor="+cursor+"&count="+count,string.Empty);

            XmlDocument dom = new XmlDocument();
            dom.LoadXml(retMsg);
            XmlNodeList nodes = dom.SelectNodes("users/user");

            int len = nodes.Count;
            Person[] fans=new Person[len];
            int i = 0;
            foreach (XmlNode node in nodes)
            {
                  fans[i++]= new Person (node.OuterXml);
            }

            XmlNode xcursor = dom.SelectSingleNode("users/next_cursor");
            cursor = xcursor.InnerText;

            return fans;
        }
        public Person[] GetUserDetails(string userid)
        {
            string retMsg;
            string url = basic + "users/show.xml";
            retMsg = oauth.oAuthWebRequest(oAuthSina.Method.GET, url+"?"+ "user_id=" + userid, string.Empty);
            Person ret = new Person(retMsg);
            Person[] tmp = new Person[1];
            tmp[0] = ret;
            return tmp;
        }
     }
}
